package com.ctrip.utils;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

public class JsInServer
{  
      
    public static void main(String[]arg)throws IOException
    {  
        // 得到一个ScriptEngine对象  
        ScriptEngineManager maneger = new ScriptEngineManager();
        ScriptEngine engine = maneger.getEngineByName("JavaScript");
          
        // 读js文件  
        String jsFile = "F:\\workspace-set\\idea\\grab-client\\h5\\captcha.min.e84c1c22.js";
        FileInputStream fileInputStream = new FileInputStream(new File(jsFile));
        Reader scriptReader = new InputStreamReader(fileInputStream, "utf-8");
          
        try  
        {  
            engine.eval(scriptReader);  
            if (engine instanceof Invocable)
            {  
                // 调用JS方法  
                Invocable invocable = (Invocable)engine;  
                String result = (String)invocable.invokeFunction("hello", "张三");
                System.out.println(result);  
                System.out.println(result.length());  
            }  
        }  
        catch (Exception e)  
        {  
            e.printStackTrace();  
        }  
        finally  
        {  
            scriptReader.close();  
        }  
    }  
}  